# -*- coding: utf-8 -*-

# pyColorize is a port of android game colorize using pygame and numpy.






###############################################################################
#  Copyright (C) 2002-2007  Yango http://usuarios.multimania.es/sisar
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
################################################################################


import os

import sys
import getopt
import math
import pygame
import random
import time
import numpy as array
import pygame.font
import pygame.surface

version="0.0.1"
rectSz=(20,20)
size=(300,300)
colors=[(255,0,0),(0,255,0),(0,0,255),(255,255,0),(0,255,255)]
lstConsumed=[]
lstStatus=array.zeros([int(size[0]/rectSz[0]),int(size[1]/rectSz[1])],int)
lstVisited=array.zeros([int(size[0]/rectSz[0]),int(size[1]/rectSz[1])],int)
hasWin=False



screen=0
movements=0

def checkWin():
  global lstStatus
  global lstVisited
  for i in range(lstStatus.shape[0]):
    for j in range (lstStatus.shape[1]):
      if(lstVisited[i][j]!=1):
	return False
  return True


def gameprint(text,xx,yy,color,fsize=32):
   font = pygame.font.SysFont("Arial",fsize)
   ren = font.render(text,1,color)
   screen.blit(ren, (xx,yy))

def drawGrid(background=(0,0,0),line=(255,255,0)):
   pygame.draw.rect(screen ,background,((0,0),size))
   i=0
   while i < size[1]:
       pygame.draw.line(screen,line,(0,i),(size[0],i))
      
       i=i+rectSz[1]
   i=0
   while i < size[0]:
       pygame.draw.line(screen,line,(i,0),(i,size[1]))

       i=i+rectSz[0]


def paintSquare(coord, color=(255,255,0),border=False):
  orig=((coord[0] * rectSz[0]),(coord[1] * rectSz[1]))
  sz=(rectSz[0],rectSz[1])
  
  pygame.draw.rect(screen ,color,(orig,sz))
  if(border==True):
    pygame.draw.rect(screen ,(0,0,0),(orig,sz))
    sz=(rectSz[0]-1,rectSz[1]-1)
    rorig=[orig[0]+1,orig[1]+1]
    pygame.draw.rect(screen ,color,(rorig,sz))  
  
def randomMaze(percent=0.33):
  random.seed()
  for i in range(int(size[0]/rectSz[0])):
    for j in range(int(size[1]/rectSz[1])):
      if(random.random()<percent):
	paintSquare((i,j))
	
	

def randomFill():
  global lstStatus
  global lstVisited
  random.seed()
  for j in range(int(size[1]/rectSz[1])):
    for i in range(int(size[0]/rectSz[0])):
      c=random.randint(0,len(colors)-1)
      paintSquare((i,j),colors[c])
      lstStatus[i][j]=c
      
      
def paintStatus():
  global lstStatus
  global lstVisited
  for i in range(lstStatus.shape[0]):
    for j in range (lstStatus.shape[1]):
      paintSquare((i,j),colors[lstStatus[i][j]],border=(lstVisited[i][j]==1))
  paintIndicators()
   
def step(c):
  global lstStatus
  global lstVisited
  for i in range(lstVisited.shape[0]):
    for j in range (lstVisited.shape[1]):
      if lstVisited[i][j] == 1:
	lstStatus[i][j]=c
  
  
  
  
  done=True
  while done==True:
    done=False
    cpyLstStatus=array.copy(lstStatus)
    cpyLstVisited=array.copy(lstVisited)
    
    for i in range(lstStatus.shape[0]):
      for j in range (lstStatus.shape[1]):
	if(lstVisited[i][j]==1):
	  if (i+1)< lstStatus.shape[0] and lstVisited[i+1][j] == 0:
	    if lstStatus[i+1][j] == lstStatus[i][j]:
	      #same color
	      cpyLstVisited[i+1][j]=1
	      done=True
	  if (j+1)< lstStatus.shape[1] and lstVisited[i][j+1] == 0:
	    if lstStatus[i][j+1] == lstStatus[i][j]:
	      #same color
	      cpyLstVisited[i][j+1]=1
	      done=True
	  if (((i+1)< lstStatus.shape[0]) and ((j+1)< lstStatus.shape[1]))  and lstVisited[i+1][j+1] == 0:
	    if lstStatus[i+1][j+1] == lstStatus[i][j]:
	      #same color
	      cpyLstVisited[i+1][j+1]=1
	      done=True
	  if (((i-1)> 0) and ((j-1)> 0))  and lstVisited[i-1][j-1] == 0:
	    if lstStatus[i-1][j-1] == lstStatus[i][j]:
	      #same color
	      cpyLstVisited[i-1][j-1]=1
	      done=True
	  if (i-1)>0 and lstVisited[i-1][j] == 0:
	    if lstStatus[i-1][j] == lstStatus[i][j]:
	      #same color
	      cpyLstVisited[i-1][j]=1
	      done=True
	  if (j-1)>0 and lstVisited[i][j-1] == 0:
	    if lstStatus[i][j-1] == lstStatus[i][j]:
	      #same color
	      cpyLstVisited[i][j-1]=1
	      done=True
	#paintSquare((i,j),colors[lstStatus[i][j]])
    lstStatus=array.copy(cpyLstStatus)
    lstVisited=array.copy(cpyLstVisited)
  
  paintStatus()
      
     

def paintIndicators():
  global screen
  global size
  global colors
  global rectSz
  global movements
  global hasWin
  for i in range(len(colors)):
    orig=( rectSz[0] * i, size[1] +10  )
    #print orig
    pygame.draw.rect(screen ,colors[i],(orig,rectSz))
    gameprint(str(i),(rectSz[0] * i)+5,size[1] +10,(0,0,0))
  
  #clen area
  orig=[(rectSz[0] * len(colors))+5,size[1] +10]
  sz=[size[0],size[1]+60]
  
  #print "sz: " + str(sz)
  
  pygame.draw.rect(screen ,(0,0,0),(orig,sz))
  gameprint("Mov: " + str(movements),(rectSz[0] * len(colors))+5,size[1] +10,(255,255,255),18)
  hasWin=checkWin()
  if(hasWin):
    gameprint("ENDED in " + str(movements),0,int(size[1]/2),(255,255,255),32)


def main(argv=None):
  
    pygame.init()
    global screen
    global rectSz
    global size
    global movements
    global hasWin
    
    resize=list(size)
    resize[1]=resize[1]+60
    screen = pygame.display.set_mode(resize)
  
    total=0
    if argv is None:
        argv = sys.argv
        
        
    
   
      
    drawGrid()      
    randomFill()
    paintIndicators()
    lstVisited[0][0]=1
    
    
    pygame.display.flip() 
    """print lstStatus
    step(lstStatus[0][0])"""
    print lstStatus
    cpyLstStatus=[]
    
    
    autoplay=False
    while True:
      
      #randomMaze()
      pygame.display.flip()
      if(autoplay==True):
	autoplay=autoplay and hasWin==False
	movements=movements+1
	c=random.randint(0,len(colors)-1)
	pygame.time.wait(100)
	
	step(c)
	
      for evento in pygame.event.get():
	
	
	if evento.type == pygame.KEYDOWN:
	  key=evento.key-pygame.K_0
	  if(key>=0) and (key<len(colors)) and hasWin==False:
	    movements=movements+1
	    cpyLstStatus=array.copy(lstStatus)
	    step(key)
	    
	"""if evento.type == pygame.KEYDOWN and evento.key == pygame.K_1:
	  cpyLstStatus=array.copy(lstStatus)
	  step(1)
	if evento.type == pygame.KEYDOWN and evento.key == pygame.K_2:
	  cpyLstStatus=array.copy(lstStatus)
	  step(2)"""
	if evento.type == pygame.KEYDOWN and evento.key == pygame.K_LEFT:
	  for i in range(lstStatus.shape[0]):
	    for j in range (lstStatus.shape[1]):
	      paintSquare((i,j),colors[cpyLstStatus[i][j]])
	if evento.type == pygame.KEYDOWN and evento.key == pygame.K_RIGHT:
	  paintStatus()
	if evento.type == pygame.KEYDOWN and evento.key == pygame.K_q:
	  sys.exit()
	print lstStatus
	    
    
    """
    while True:
      drawGrid()
      randomFill()
      #randomMaze()
      pygame.display.flip()
      for evento in pygame.event.get():
	if evento.type == pygame.KEYDOWN and evento.key == pygame.K_q:
	    sys.exit()
   """


if __name__ == "__main__":
    sys.exit(main())